//
//  LoginViewController.swift
//  SchoolDemo
//
//  Created by rimi on 16/9/29.
//  Copyright © 2016年 YQ. All rights reserved.
//

import UIKit
import SVProgressHUD

class LoginViewController: UIViewController {
//登录按钮属性
    @IBOutlet weak var longinBtn: UIButton!
    //密码输入框
    @IBOutlet fileprivate weak var PasswordT: UITextField!
    //账号输入框
    @IBOutlet fileprivate weak var accountT: UITextField!
    
    //懒加载活动指示器
    lazy var  activity: UIActivityIndicatorView = UIActivityIndicatorView (activityIndicatorStyle: UIActivityIndicatorViewStyle.whiteLarge)
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

      setupUI()
        //添加活动指示器
        activity.center = view.center
        activity.color = #colorLiteral(red: 0.8078431487, green: 0.02745098062, blue: 0.3333333433, alpha: 1)
        view.addSubview(activity)
       
    }
     
    //数据请求
    func downloadData() {
  
        
    }
    
    //设置UI
    func setupUI() {
        //设置圆角半径
        longinBtn.layer.cornerRadius = 5
        //设置边框
        longinBtn.layer.borderColor = UIColor.gray.cgColor
        longinBtn.layer.borderWidth =  1
        //设置输入框的左边视图
        accountT.leftView = setupLeftView(imageName: "icon_user")
        accountT.leftViewMode = .always
        
        PasswordT.leftView = setupLeftView(imageName: "icon_password")
        PasswordT.leftViewMode = .always
    }
    //左边视图
    fileprivate func setupLeftView(imageName: String) -> UIView {
        let bgView = UIView(frame: CGRect(x: 0, y: 0, width: 44, height: 44))
        //第一张图片视图
        let firstV = UIImageView(image: UIImage(named: imageName))
        firstV.center = CGPoint(x: firstV.bounds.width / 2 + 10, y: 22)
        bgView.addSubview(firstV)
        
        //第二张图片
        let towV = UIImageView(image: UIImage(named: "line_edit_sep"))
        towV.center = CGPoint(x: firstV.frame.maxX + towV.bounds.width / 2 + 10, y: 22)
        bgView.addSubview(towV)
        
        return bgView
        
    }
    
    //登录按钮监听回调方法
    @IBAction func LonginClicked(_ sender: UIButton) {
        //先要判断用户是否已经设置服务器IP地址
        if baseURLStr == nil || baseURLStr! == "zao/interface/" {
            SVProgressHUD.setMinimumDismissTimeInterval(2)
            SVProgressHUD.setDefaultStyle(.dark)
            SVProgressHUD.showInfo(withStatus: "请先设置学校Ip地址")
            print("请先设置学校Ip地址")
            return
        }
        guard let acc = accountT.text, acc != "" else {
            //提醒用户账号不能为空
            SVProgressHUD.setMinimumDismissTimeInterval(2)
            SVProgressHUD.setDefaultStyle(.dark)
            SVProgressHUD.showInfo(withStatus: "账号不能为空")
//            SVProgressHUD.dismiss(withDelay:2)
            print("账号不能为空")
            return
        }
        guard let pass = PasswordT.text, pass != "" else {
            SVProgressHUD.setMinimumDismissTimeInterval(2)
            SVProgressHUD.setDefaultStyle(.dark)
            SVProgressHUD.showInfo(withStatus: "密码不能为空")
            print("密码不能为空")
            return
        }
        //开启活动
        activity.startAnimating()
        //拼接地址
        let urlStr = baseURLStr! + "ZH-schoolname-S-login"
        //参数字典
        let param = ["code":acc,"password":pass]
        //请求数据
        HSNetWorkTools.shared.downloadData(url: urlStr, parameters: param) {[weak self](data, error) in
            //到这里请求已经回调，关闭活动监视器
            self?.activity.stopAnimating()
            
            if error != nil{
                SVProgressHUD.setMinimumDismissTimeInterval(2)
                SVProgressHUD.setDefaultStyle(.dark)
                SVProgressHUD.showInfo(withStatus: "网络请求失败")
                print("网络数据请失败")
                return
            }
//            print(data)
            //获得返回数据
            guard let dict = data as? NSDictionary else {
            
                return
            
            }
            //将类型转换为Int
            let result = dict["result"] as! Int
            //判断
            switch result {
            case 0:
                //保存数据
                dict.write(toFile: saveUserInfoPath, atomically: true)
            //跳转到下一个页面
            //关闭活动指示器
              self?.activity.stopAnimating()
                //获得下一个页面控制器
                UIApplication.shared.keyWindow?.rootViewController = HSDrawerController()
                //记录登录状态
                UserDefaults.standard.set(true, forKey: islogin)
                
                
            case 1:

                
                print("账号或密码错误")
            default:
                break
            }
        }
//        print(baseURLStr)
    }
//设置按钮监听回调方法
    @IBAction func LoginSettingBtnClicked(_ sender: UIButton) {
//        print("sss")
//        //弹窗输入
        let alertVc = UIAlertController(title: "请输入学校服务器的IP地址", message: nil, preferredStyle: .alert)
       
        //添加文本输入框
        alertVc.addTextField { (textF) in
            textF.placeholder = "IP地址"
            textF.borderStyle = .none
            textF.textAlignment = .center
            //获得保存的内容
            let saveIp = UserDefaults.standard.value(forKey: xx_ipKey)
            textF.text = saveIp as? String
        }
        //确定按钮
        alertVc.addAction(UIAlertAction(title: "确定", style: .default, handler: { (_) in
            //获得输入框的内容
            let IpText = alertVc.textFields?[0].text
            //保存字符串
            UserDefaults.standard.set(IpText, forKey: xx_ipKey)
        }))
        //取消按钮
        alertVc.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil))
        
        
        present(alertVc, animated: true, completion: nil)
       
    }
    
    //调整状态栏模式
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }
  
}
extension LoginViewController {
    //回收键盘
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        view.endEditing(true)
    }
}
